/*
 * @Author: xiaoliang
 * @Date: 2025-03-05 15:52:15
 * @LastEditors: xiaoliang
 * @LastEditTime: 2025-03-05 15:52:35
 * @FilePath: /codepiece/arrayflat.js
 * @Description: 数组扁平化
 */

function customFlat(array, depth = 1) {
  if (depth === 0) return array.slice();
  return array.reduce((acc, val) => {
    return acc.concat(Array.isArray(val) ? customFlat(val, depth - 1) : val);
  }, []);
}
// 使用示例
const nestedArray = [1, [2, [3, [4]], 5]];
console.log(customFlat(nestedArray, 1)); // [1, 2, [3, [4]], 5]
console.log(customFlat(nestedArray, 2)); // [1, 2, 3, [4], 5]
console.log(customFlat(nestedArray, Infinity)); // [1, 2, 3, 4, 5]